'use strict';

var mysql = require("mysql");
var logger = require('../utils/log');
var constant = require('../utils/constant');

var pool = null;

function init(config){
    pool = mysql.createPool({
        host: config.HOST,
        user: config.USER,
        password: config.PSWD,
        database: config.DB,
        port: config.PORT,
    });
};

function setRoomInfo(roomInfo, callback) {
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_rooms(room_id,room_no,conf,ip,http_port,socket_port,creator,create_time) \
                VALUES({0},'{1}','{2}','{3}','{4}','{5}',{6},{7})";
    sql = sql.format(roomInfo.roomId, roomInfo.roomNo, roomInfo.conf, roomInfo.ip, roomInfo.httpPort, roomInfo.socketPort, roomInfo.creator, roomInfo.createTime);
    query(sql,function(err, row, fields){
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        }else{
            callback(constant.CODE_SUCCESS, row);
        }
    });
};

function updateRoomResult(roomInfo, playInfo, result, callback) {
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_rooms SET plays_info = '{0}', result = '{1}' WHERE room_id = '{2}'";
    sql = sql.format(playInfo, result, roomInfo.roomId);
    query(sql,function(err, row, fields){
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        }else{
            callback(constant.CODE_SUCCESS, row);
        }
    });
};

function getRoomInfo(roomId, callback) {
    callback = callback == null? nop:callback;
    var sql = 'SELECT * FROM t_rooms WHERE room_id = "' + roomId + '"';
    query(sql, function(err, rows, fields) {
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        } else {
            callback(constant.CODE_SUCCESS, rows[0]);
        }
    });
};

function setUsersRoomRecord(userIds, roomId, callback) {
    var createTime = Date.now();
    var userRoom = {};
    userIds.forEach(function (userId, index) {
        userRoom = {};
        userRoom.userId = userId;
        userRoom.roomId = roomId;
        userRoom.createTime = createTime;

        setUserRoomRecord(userRoom, null);
    });
};

function setUserRoomRecord(userRoom, callback) {
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_user_room(user_id,room_id,create_time) \
                VALUES('{0}','{1}',{2})";
    sql = sql.format(userRoom.userId, userRoom.roomId, userRoom.createTime);
    query(sql,function(err, row, fields){
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        }else{
            callback(constant.CODE_SUCCESS, row);
        }
    });
};

function getUserRoomRecords(userId, callback) {
    callback = callback == null? nop:callback;

    var sql = 'SELECT * FROM t_users a INNER JOIN t_rooms b ON a.room_id = b.room_id WHERE a.user_id = "' + userId + '" OREDR BY b.create_time DESC LIMIT 0, 10';
    query(sql, function(err, rows, fields) {
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        } else {
            callback(constant.CODE_SUCCESS, rows[0]);
        }
    });
};

function setUserInfo(userInfo, callback) {
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_users(user_id,unionid,account,name,sex,headimg,ip,coins,gems,create_time,province,city) \
                VALUES('{0}','{1}','{2}','{3}',{4},'{5}','{6}',{7},{8},{9},'{10}','{11}')";
    var createTime = Date.now();
    sql = sql.format(userInfo.userId,userInfo.unionid, userInfo.account, userInfo.name, userInfo.sex, userInfo.headimg, userInfo.ip, userInfo.coins, userInfo.gems, createTime, userInfo.province, userInfo.city);
    query(sql,function(err, row, fields){
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        }else{
            callback(constant.CODE_SUCCESS, 0);
        }
    });
};

function getUserInfo(userId, callback) {
    callback = callback == null? nop:callback;
    var sql = 'SELECT * FROM t_users WHERE user_id = "' + userId + '"';
    query(sql, function(err, rows, fields) {
        if(err){
            callback(constant.CODE_MYSQL_ERROR, null);
        } else {
            callback(constant.CODE_SUCCESS, rows[0]);
        }
    });
};

exports.init = init;

exports.setRoomInfo = setRoomInfo;
exports.updateRoomResult = updateRoomResult;
exports.getRoomInfo = getRoomInfo;

exports.setUsersRoomRecord = setUsersRoomRecord;
exports.setUserRoomRecord = setUserRoomRecord;
exports.getUserRoomRecords = getUserRoomRecords;

exports.setUserInfo = setUserInfo;
exports.getUserInfo = getUserInfo;

function query(sql,callback){
    logger.debug('----------mysql', sql);
    pool.getConnection(function(err,conn){
        if(err){
            logger.error('----------mysql', err);
            callback(err,null,null);
        }else{
            conn.query(sql,function(qerr,vals,fields){
                //释放连接
                conn.release();
                //事件驱动回调
                callback(qerr,vals,fields);
            });
        }
    });
};

function nop(a,b,c,d,e,f,g){};